package com.zjdiepu.www.security.sign.rsa;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.zjdiepu.www.security.sign.ISign;
import com.zjdiepu.www.security.sign.lang.SignUtil;

/**
 * RSA签名认证<br>
 * 验证签名正确性<br>
 * 签名生成：通过客户端与服务端约定的key以及加密算法对内容字符进行加密生成。<br>
 * 验证方式：在服务端获取签名，使用客户端与服务端约定的key以及加密算法对内容进行加密，
 * 对比加密得到的字符与原签名字符是否一致，一致则验证成功，不一致则验证失败。<br>
 * <p> 注意： 客户端提交请求时不需要提交key
 *
 * @author xiongxiaotun
 * @version 1.0
 */
public class RsaSign implements ISign {

    @Override
    public boolean verifySign(Map<String, Object> paramMap, String targetSign, String key, String secretKey, String signCovenantKey) {
    	String comparedString = SignUtil.sortMapToString(paramMap, key, signCovenantKey);
        if (StringUtils.equals(comparedString, targetSign)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean verifySign(Object obj, String targetSign, String key, String secretKey, String signName, String signCovenantKey) {
    	Map<String, Object> signMap = SignUtil.getSignMap(new HashMap<String, Object>(), obj, obj.getClass(), signName);
    	String comparedString = SignUtil.sortMapToString(signMap, key, signCovenantKey);
        if (StringUtils.equals(comparedString, targetSign)) {
            return true;
        }
        return false;
    }
    
    @Override
    public String generateSign(Object obj, String signKey, String secretKey, String signName, String signCovenantKey, boolean isRsaResp) {
    	if(obj == null) {
    		return null;
    	}
        Map<String, Object> map = SignUtil.getSignMap(new HashMap<String, Object>(), obj, obj.getClass(), signName);
        return generateSign(map, signKey, secretKey, signCovenantKey, isRsaResp);
    }


    @Override
    public String generateSign(Map<String, Object> map, String signKey, String secretKey, String signCovenantKey, boolean isRsaResp) {
    	if(isRsaResp) {
    		return RsaProvider.signWithPri(SignUtil.sortMapToString(map, signKey, signCovenantKey), secretKey);
    	} else {
    		return RsaProvider.signWithPub(SignUtil.sortMapToString(map, signKey, signCovenantKey), secretKey);
    	}
    }
}
